package presstrack
{
	import flash.net.Responder;
	
	import mx.collections.ArrayCollection;
	import mx.utils.ObjectUtil;
	
	import org.presstrack.service.*;
	
	[RemoteClass(alias="presstrack.OrderPartClass")]
	
	[Bindable]
	public class OrderPartClass
	{
		public var index:int;
		public var products:ArrayCollection;
		public var tasks:ArrayCollection;
		public var relations:ArrayCollection;
		
		public var press_task:TaskClass;
		public var paper_task:TaskClass;
		
		public function OrderPartClass(part:Object = null)
		{
			press_task = new TaskClass;
			paper_task = new TaskClass;
			if (part != null) setFromObject(part);
		}
		
		public function setFromObject(ob:Object):void{
			if (ob.hasOwnProperty("index"))
				index = Number(ob.index);
				
			if (ob.hasOwnProperty("products")) {
				products = new ArrayCollection();
				for each(var p:Object in ob.products) {
					var product:ProductClass = new ProductClass(p);
					products.addItem(product);
				}
				products.refresh();				
			}
			
			if (ob.hasOwnProperty("tasks")) {
				tasks = new ArrayCollection();
				for each(var t:Object in ob.tasks) {
					var task:TaskClass = new TaskClass(t);
					tasks.addItem(task);
					if (task.label == "печать")
						press_task = task;
					else if (task.label == "бумага")
						paper_task = task;	
				}
				tasks.refresh();				
			}
			
			if (ob.hasOwnProperty("relations")) {
				relations = new ArrayCollection(ob.relations);
			}
		}
		
		public function addProduct(params		:Array, 
								   resFunc		:Function	= null, 
								   faultFunc	:Function 	= null):void 
		{
			var product:ProductClass = new ProductClass();
			product.label	= params["label"];
			product.size	= params["size"];
			product.run		= params["run"];
			product.color	= params["color"];
			product.group	= index;
			product.order	= CrudService.curOrder.iOrderId;
			
			CrudService.crud.srv.call("PressTrack.AddProduct", new Responder(onResult, onFault), 
									  product.order, product.group, product.label, 
									  product.run, product.size, product.color);
			
			function onResult(result:Object):void 
			{
				if (result.status == true)
				{
					product.idproduct = result.idproduct;
					products.addItem(product);
					products.refresh();					
																	
					for each (var rel:Object in result.relations)
					{
						var relation:RelationClass = new RelationClass(rel);
						relations.addItem(relation);
					}
					relations.refresh();
					
					autoUpdateTasks();	
					if (resFunc != null)
					{
						resFunc();	
					}								
				}
				else
				{
					faultFunc(result.message);
				}
			}
			
			function onFault(e:Object):void 
			{
				faultFunc(ObjectUtil.toString(e));
			}
			
		}
		
		public function deleteProduct( product:ProductClass, resFunc:Function = null, faultFunc:Function = null  ) : void {
			CrudService.crud.srv.call("PressTrack.RemoveProduct", new Responder(onResult, onFault), product.idproduct);
			
			function onResult(result:String) : void {
				if (result == "successful")
				{
					for each(var rel:Object in relations)
					{
   						if (rel.product_id == product.idproduct) {
   							relations.removeItemAt(relations.getItemIndex(rel));
   						}   									
   					}	
   					relations.refresh();
   					
   					products.removeItemAt(products.getItemIndex(product));
					products.refresh();
									
					autoUpdateTasks();				
					if (resFunc != null) resFunc();										
				}
				else
					faultFunc(result);
			}
			
			function onFault(e:Object) : void {
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		public function addTask(ts:TaskClass, resFunc:Function = null, faultFunc:Function = null) : void 
		{
			CrudService.crud.srv.call("PressTrack.AddTask", new Responder(onResult, onFault), ts.order, index, ts.label, ts.value, ts.section);
			
			function onResult(result:Object) : void {
				if (result.status == true)
				{
					ts.idtask = result.idtask;
					tasks.addItem(ts);
					tasks.refresh();
					
					for each (var rel:Object in result.relations)
					{
						var relation:RelationClass = new RelationClass(rel);
						relations.addItem(relation);
					}
					relations.refresh();
					
					if (resFunc != null) resFunc();
				}
				else
					faultFunc(result.message);
			}
			
			function onFault(e:Object) : void {
				faultFunc(ObjectUtil.toString(e));
			}
		}		
		
		public function deleteTask(ts:TaskClass, resFunc:Function = null, faultFunc:Function = null) : void {
			CrudService.crud.srv.call("PressTrack.RemoveTask", new Responder(onResult, onFault), ts.idtask);
			
			function onResult(result:String) : void {
				if (result == "successful")
				{
					for each (var rel:Object in relations) {
						if (rel.task_id == ts.idtask) {
							relations.removeItemAt(relations.getItemIndex(rel));									
						}
					}
					relations.refresh();
					
					tasks.removeItemAt(tasks.getItemIndex(ts));
					tasks.refresh();				
				}
			}
			
			function onFault(e:Object) : void {
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		public function addRelation(idtask:int, idproduct:int, resFunc:Function = null, faultFunc:Function = null ) : void {
			var res:Boolean = new Boolean(false);
			for each(var r:Object in relations) 
			{
				if (r.product_id == idproduct && r.task_id == idtask) {
    				res = true;
    					break;
    			}
    		}
    		if (!res) {
    			CrudService.crud.srv.call("PressTrack.AddRelation", new Responder(onResult, onFault), idproduct, idtask);					
    		}
			
			
			function onResult(id:String):void {
				if ( Number(id) ) {
					var rel:RelationClass = new RelationClass();
					rel.task_id = idtask;
					rel.product_id = idproduct;
					rel.idrelation = Number(id);			
					relations.addItem(rel);
					relations.refresh();			
				}
				else
					faultFunc(id);
			}
			
			function onFault(e:Object) : void {
				faultFunc(ObjectUtil.toString(e));
			}
		}
		
		public function unRelation(idproduct:int, idtask:int, resFunc:Function = null, faultFunc:Function = null) : void {
			for each (var r:Object in relations)	
			{
				if (r.product_id == idproduct && r.task_id == idtask){
					deleteRelation(r);
					break;
				}
			}
		}
		
		/**
		 * autoUpdateTasks
		 * 
		 * метод вызывается при добавлении / редактировании изделий
		 * и автоматически обновляет следующие параметры:
		 * 
		 * в задании на печать - красочность;
		 * в задании на вывод форм - кол-во форм;
		 * 
		 * */
		public function autoUpdateTasks():void
		{
			// определяем красочность
						
			var arFrontColor:ArrayCollection	= new ArrayCollection();
			var arBackColor:ArrayCollection		= new ArrayCollection();
		
			for each (var pr:ProductClass in products) 
			{
				var temp:Array = pr.color.split(" + ");
				if(temp[0].toString() != "0")
				{
					var ar_face:Array = temp[0].toString().split(",");
					for each (var f:String in ar_face) 
					{
						if (arFrontColor.contains(f) == false)
						{
							arFrontColor.addItem(f);
						}
					}
				}
				
				if (temp.length > 1) 
				{	
					if (temp[1].toString() != "0")
					{
						var ar_back:Array = temp[1].toString().split(",");
						for each (var b:String in ar_back) 
						{
							if (arBackColor.contains(b) == false)
							{
								arBackColor.addItem(b);
							}
						}		
					}
				}						
			}
			
			var press_color:String = "красочность : " 
								   + arFrontColor.length.toString() 
								   + " + " 
								   + arBackColor.length.toString() 
								   + " (" 
								   + arFrontColor.source.join(",") 
								   + " + " 
								   + arBackColor.source.join(",") 
								   + ")";
			
			// определяем количество форм
			
			// количество красок
			var color_num:int = arFrontColor.length + arBackColor.length;
			// тираж
			var ar_press_value:Array	= press_task.value.split("\r");
			var ar_run:Array 			= ar_press_value[1].split(" : ");
			var press_run:String 		= ar_run[1];	
			ar_run		 				= press_run.split(/,/);
			
			var ctp_num:int = 0;
			for each(var r:Object in ar_run)
			{
				var forms:int = new int(color_num); 
				var ar_temp:Array = r.split(/x/);
				if (ar_temp.length > 1)
				{
					var pattern:RegExp = /[^0-9]/g; 
					ar_temp[0] = ar_temp[0].replace(pattern,'');
					var num:int = forms * Number(ar_temp[0]);
						
					if (ar_temp[1].search("c/c") > 0)
					{
						num = num / 2;
					}
						
					forms = num;
				}
				else if (ar_temp.length == 1)
				{
					if (ar_temp[0].search("c/c") > 0)
					{
						forms = forms / 2;
					}
				}
					
				ctp_num += forms;
			}
			
			var form_num:String = "форм : " + ctp_num.toString();
			// обновляем задания
			
			for each (var tsk:TaskClass in tasks)
			{
				if (tsk.label == "печать")
				{
					var ar_task:Array	= tsk.value.toString().split("\r");
					ar_task[4]			= press_color;
					tsk.value			= ar_task.join('\r');
					tsk.setValue(tsk.value);
				}
				else if (tsk.label == "вывод форм")
				{
					tsk.value			= form_num;
					tsk.setValue(tsk.value);
				}				
			}				
		}
		
		// private
		private function deleteRelation(rel:Object, resFunc:Function = null, faultFunc:Function = null) : void {
			CrudService.crud.srv.call("PressTrack.RemoveRelation", new Responder(onResult), rel.idrelation);				
			function onResult() : void {
				relations.removeItemAt(relations.getItemIndex(rel));
				relations.refresh();
    		}	
		}
	}
}